package com.autumn.aitraffic.ws;

import com.alibaba.fastjson.JSON;
import com.autumn.aitraffic.config.GetHttpSessionConfigurator;
import com.autumn.aitraffic.domain.po.Message;
import com.autumn.aitraffic.util.MessageUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers=new ConcurrentHashMap<>();

    private HttpSession httpSession;
    /**
     * 建立websocket连接后，被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config) {
        //1.将session进行保存
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String user = (String) this.httpSession.getAttribute("user");//前提是我们得在登录的时候就创建一个session,并且往里面注入值，此处我还没做
        onlineUsers.put(user,session);
        //2.广播消息。 需要将登录的所有用户推送给所有的用户
        String message = MessageUtils.getMessage(true, null, getFriends());
        broadcastAllUsers(message);
    }

    private Set getFriends() {
        return onlineUsers.keySet();
    }

    private void broadcastAllUsers(String message){
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                //获取所有用户对应的session对象
                Session value = entry.getValue();
                //发送消息
                value.getBasicRemote().sendText(message);//该方法用于发送同步消息
            }
        }
        catch (Exception e){
            //记录日志
        }
    }

    /**
     * 浏览器发送消息到服务端该方法则被调用
      * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        //将消息推送给指定用户
        Message msg = JSON.parseObject(message, Message.class);
        //获取消息接收方用户名
        String toName = msg.getToName();
        String mess = msg.getMessage();
        //获取消息接收方用户对应的session
        Session session = onlineUsers.get(toName);
        String user = (String) this.httpSession.getAttribute("user");//前提是我们得在登录的时候就创建一个session,并且往里面注入值，此处我还没做
        try {
            session.getBasicRemote().sendText(MessageUtils.getMessage(false,user,mess));
        } catch (Exception e) {
            //记录日志
        }
    }

    /**
     * 断开websocket连接时被调用
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        //1.从ollineUsers中剔除当前用户的session对象
        String user=(String)this.httpSession.getAttribute("user");
        onlineUsers.remove(user);
        //2通知其他所有用户当前用户下线了
        broadcastAllUsers(MessageUtils.getMessage(true, null, getFriends()));
    }
}
